<template>
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      :limit="limit"
      :action="action"
      :headers="headerObj"
      :accept="accept"
      name="files"
      :show-file-list="true"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :file-list="Filelist"
      :data="{ fileType: 1 }"
    >
      <template #tip v-if="tip">
        <div class="el-upload__tip">
          {{ tip }}
        </div>
      </template>
      <el-button type="primary" :icon="Upload">{{ btnName }}</el-button>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus, Upload } from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";

const emit = defineEmits(["file-uploaded", "file-remove"]);
const props = defineProps({
  tip: {
    type: String,
    default: "",
  },

  limit: {
    type: Number,
    default: 3,
  },
  id: {
    type: Number,
    default: "",
  },
  btnName: {
    type: String,
    default: "上传",
  },
  name: {
    type: String,
  },
  // 显示的附件列表
  Filelist: {
    type: Array,
    default: () => [],
  },
  accept: {
    type: String,
    default: "",
  },
});

const headerObj = ref({
  Authorization: "Bearer " + getToken(),
});

const action =
  import.meta.env.MODE === "production"
    ? `${
        import.meta.env.VITE_APP_BASE_API
      }/management-admin/file/uploadFileSimple`
    : "/admin/management-admin/file/uploadFileSimple";

const handleAvatarSuccess = (response, uploadFile) => {
  const { data } = response;

  emit("file-uploaded", { data: data[0], id: props.id, name: props.name });
};

const handleRemove = (file, fileList) => {
  emit("file-remove", { id: props.id, file: file });
};

const beforeAvatarUpload = (rawFile) => {
  let accept = props.accept;
  let str = rawFile.name;
  let index = str.lastIndexOf("\.");
  str = str.substring(index + 1, str.length);
  console.log(str);
  if (accept !== str && accept !== "") {
    ElMessage.error("上传文件格式不正确");
    return false;
  }

  console.log(rawFile);
  return true;
};
</script>

<style scoped>
.avatar-uploader .av.accept {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
